package com.lishuang.org.controller;

import com.lishuang.basic.exception.BusinessException;
import com.lishuang.basic.util.AjaxResult;
import com.lishuang.basic.util.ExcelUtil;
import com.lishuang.basic.util.PageList;
import com.lishuang.org.domain.Shop;
import com.lishuang.org.domain.ShopAuditLog;
import com.lishuang.org.dto.ShopDto;
import com.lishuang.org.query.ShopQuery;
import com.lishuang.org.service.IShopService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/shop")
@Api(value = "店铺的API", description = "店铺相关的CRUD功能")
public class ShopController {

    @Autowired
    private IShopService shopService;

    @GetMapping("/{id}")
    @ApiOperation(value = "通过ID查询")
    public Shop findOne(@PathVariable("id") Long id) {
        return shopService.loadById(id);
    }

    @GetMapping
    @ApiOperation(value = "查询所有")
    public List<Shop> findAll() {
        return shopService.loadAll();
    }

    @PostMapping
    @ApiOperation(value = "分页查询")
    public PageList<Shop> queryPage(@RequestBody ShopQuery query) {
        return shopService.queryPage(query);
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "通过ID删除数据")
    public AjaxResult delete(@PathVariable("id") Long id) {
        try {
            shopService.remove(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("删除失败");
        }

    }

    @PatchMapping
    @ApiOperation(value = "通过ids批量删除数据")
    public AjaxResult batchDelete(@RequestBody List<Long> ids) {
        try {
            shopService.batchDelete(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("批量删除失败");
        }

    }

    @PutMapping
    @ApiOperation(value = "添加或者修改(通过有无ID区分)")
    public AjaxResult addOrUpdate(@RequestBody Shop shop) {
        try {
            if (shop.getId() == null) {
                shopService.save(shop);
            } else {
                shopService.update(shop);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("操作失败");
        }
    }

    /**
     * 接口：店铺入驻
     *
     * @param
     * @return
     */
    @PostMapping("/settlement")
    @ApiOperation(value = "店铺入驻")
    //前端传递的是数组 - 后端既可以用数组,也可以用集合
    public AjaxResult settlement(@RequestBody Shop shop) {
        try {
            shopService.settlement(shop);
            return new AjaxResult();//true + "操作成功"
        } catch (BusinessException e) {
            //e.printStackTrace();
            return new AjaxResult(false, "入驻失败，" + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, "系统繁忙，请稍后重试!!!");
        }
    }

    /**
     * 审核驳回
     *
     * @param shopAuditLog
     * @return
     */
    @PostMapping("/audit/reject")
    @ApiOperation(value = "审核驳回")
    public AjaxResult reject(@RequestBody ShopAuditLog shopAuditLog) {
        try {
            shopService.reject(shopAuditLog);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("操作失败！" + e.getMessage());
        }
    }

    /**
     * 审核通过
     *
     * @param shopAuditLog
     * @return
     */
    @PostMapping("/audit/pass")
    @ApiOperation(value = "审核通过")
    public AjaxResult pass(@RequestBody ShopAuditLog shopAuditLog) {
        try {
            shopService.pass(shopAuditLog);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("操作失败！" + e.getMessage());
        }
    }

    /**
     * 数据导出
     *
     * @param response
     * @return
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) {
        try {
            List<Shop> shops = shopService.loadAll();
            ExcelUtil.exportExcel(shops, null, "店铺信息", Shop.class, "shop.xlsx", response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 数据导入
     *
     * @param file
     * @return
     */
    @PostMapping("/import")
    public void importExcel(@RequestPart("file") MultipartFile file){
        //String file = "F:\\文件名.xls";
        //解析excel，
        List<Shop> list = ExcelUtil.importExcel(file,0,1,Shop.class);
        //也可以使用MultipartFile,使用 FileUtil.importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass)导入
        System.out.println("导入数据一共【"+list.size()+"】行");
        for (Shop shop:list) {
            System.out.println(shop);
        }
        //保存到数据库中[自己实现，提示：动态sql 批量插入]
    }

    /**
     * 柱状图实现
     *
     * @param
     * @return
     */
    @GetMapping("/echarts")
    public List<ShopDto> echartsData(){
        List<ShopDto> shopDtos = shopService.getCountByState();
        return shopDtos;
    }

    /**
     * 店铺激活
     *
     * @param id
     * @return AjaxResult
     */
    @GetMapping("/active/{id}")
    public void active(@PathVariable("id") Long id, HttpServletRequest request,HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        try {
            Shop shop = shopService.loadById(id);
            if (shop.getState()==2) {
                shop.setState(3);
                shopService.update(shop);
            }

            response.getWriter().write("激活成功,3秒后跳转到登录页面。。。");
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("激活失败，请联系管理员。。。");
        }finally {
            response.setHeader("refresh","3;URL='http://localhost:8081/#/login'");
        }


    }



}
